//
//  WYFJSCommand.m
//  NetEaseFinancial
//
//  Created by 吴玉峰 on 8/17/15.
//  Copyright (c) 2015 吴玉峰. All rights reserved.
//

#import "WYFJSCommand.h"

#import "WYFJSBridge.h"

static NSString *const PARAM_SERIAL = @"serial";
static NSString *const PARAM_NAME = @"name";
static NSString *const PARAM_PARAMS = @"params";
static NSString *const PARAM_RESULT = @"result";
static NSString *const PARAM_TYPE = @"type";

@class WYFJSBridge;

@interface WYFJSCommand ()

@property (nonatomic, weak) WYFJSBridge *jsBridge;

@end

@implementation WYFJSCommand

- (instancetype)initCommandWithJsonObj:(NSDictionary *)jsonObj jsBridge:(WYFJSBridge *)jsBridge {
    if ((self = [super init])) {
        self.jsBridge = jsBridge;
        self.serial = jsonObj[PARAM_SERIAL];
        self.name = jsonObj[PARAM_NAME];
        self.params = jsonObj[PARAM_PARAMS];
        self.result = jsonObj[PARAM_RESULT];
        self.type = jsonObj[PARAM_TYPE];
    }

    return self;
}

- (instancetype)initCommandWithName:(NSString *)name params:(NSDictionary *)params type:(NSNumber *)type {
    if ((self = [super init])) {
        self.serial = [WYFJSBridge createSerial];
        self.name = name;
        self.params = params;
        self.type = type;
    }

    return self;
}

- (NSString *)description {
    NSDictionary *dict =
        [NSDictionary dictionaryWithObjectsAndKeys:self.serial, PARAM_SERIAL, self.type, PARAM_TYPE, self.name, PARAM_NAME,
                                                   self.params, PARAM_PARAMS, self.result, PARAM_RESULT, nil];

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the
                                                                                          // readability of the generated string
                                                         error:&error];

    if (!jsonData) {
        NSLog(@"Command Got an error: %@", error);
        return nil;
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return jsonString;
    }
}

//
///**
// * 释放该命令保存的内容, 防止被再次触发
// */
// public void release() {
//    this.serial = null;
//    this.name = null;
//    this.params = null;
//    this.result = null;
//    this.type = 0;
//}
//
//
/**
 * 设置本次native调用的结果
 *
 * @param result
 */
- (void)setResultForJs:(NSDictionary *)result {
    NSLog(@"setResultForJs------------------");
    self.result = result;
    int intType = [self.type intValue];
    self.type = [NSNumber numberWithInt:EXECUTE_NATIVE_CALLBACK];
    if (intType != EXECUTE_NATIVE_FUNCTION_SYNC) {
        [self.jsBridge handleCommand:self];
    }
}

@end
